package org.util;

import java.lang.reflect.Field;

public class BeanUtil {
    public static void setProperty(Object bean, String propertyName, Object value){
        try {
            Class<?> aClass = bean.getClass();
            Field field = aClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            field.set(bean,value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static Object getProperty(Object bean, String propertyName){
        Object value = null;
        try {
            Class<?> aClass = bean.getClass();
            Field field = aClass.getDeclaredField(propertyName);
            field.setAccessible(true);
            value = field.get(bean);
        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }

    public static void copyProperties(Object source, Object target){
        Class<?> aClass = source.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(source);
                field.set(target,value);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
